# -*- coding: utf-8 -*-
import requests
from django.conf import settings
import os
from django.http import Http404


def save_image(url, path):
    res = requests.get(url)
    if res.status_code != 200:
        raise Http404('获取头像失败')
    name = settings.RANDOM_NAME
    file_name = settings.STATICFILES_DIRS[0] + os.sep + path + os.sep + name
    with open(file_name + '.png', 'wb') as f:
        f.write(res.content)
    avatar = settings.MY_URL + path + os.sep + name + '.png'
    return avatar


def save_file(file, path: str) -> str:
    name = settings.RANDOM_NAME
    file_path = settings.STATICFILES_DIRS[0] + os.sep + path + os.sep + name + '.png'
    with open(file_path, 'wb') as f:
        for chunk in file.chunks():
            f.write(chunk)
    avatar = settings.MY_URL + path + '/' + name + '.png'
    return avatar
